<template>
  <div class="code-generation-management">
    <h3>代码生成管理</h3>
    
    <a-card>
      <div class="toolbar">
        <a-button type="primary" @click="goToCustomCodeGeneration">
          <template #icon>
            <PlusOutlined />
          </template>
          新增配置
        </a-button>
      </div>
      
      <a-table 
        :dataSource="savedConfigs" 
        :columns="columns" 
        :pagination="pagination"
        :loading="loading"
        rowKey="id"
        style="margin-top: 20px;"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'generationType'">
            <span v-if="record.generationType === 'list'">列表页</span>
            <span v-else-if="record.generationType === 'detail'">详情页</span>
            <span v-else-if="record.generationType === 'modal_table'">弹框(列表)</span>
            <span v-else-if="record.generationType === 'modal_form'">弹框(表单)</span>
            <span v-else-if="record.generationType === 'list_detail'">列表+详情模版(组合版)</span>
            <span v-else-if="record.generationType === 'multi_tab_detail'">详情模版(多页签)</span>
            <span v-else>{{ record.generationType }}</span>
          </template>
          
          <template v-else-if="column.dataIndex === 'actions'">
            <a-button type="link" @click="editConfig(record)">编辑</a-button>
            <a-popconfirm
              title="确定要删除这个配置吗？"
              @confirm="deleteConfig(record)"
            >
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onActivated } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'

const router = useRouter()

// 表格列定义
const columns = [
  {
    title: '页面代码',
    dataIndex: 'pageCode',
    key: 'pageCode'
  },
  {
    title: '生成类型',
    dataIndex: 'generationType',
    key: 'generationType'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime'
  },
  {
    title: '操作',
    dataIndex: 'actions',
    key: 'actions'
  }
]

// 保存的配置数据
const savedConfigs = ref([])

// 加载状态
const loading = ref(false)

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`,
  onChange: (page, pageSize) => {
    pagination.value.current = page
    pagination.value.pageSize = pageSize
    loadSavedConfigs()
  }
})

// 加载保存的配置
const loadSavedConfigs = () => {
  loading.value = true
  try {
    // 从 localStorage 获取保存的配置
    const configs = JSON.parse(localStorage.getItem('savedCodeConfigs') || '[]')
    
    // 处理分页
    const start = (pagination.value.current - 1) * pagination.value.pageSize
    const end = start + pagination.value.pageSize
    
    savedConfigs.value = configs.slice(start, end).map(config => ({
      ...config,
      createTime: config.createTime ? new Date(config.createTime).toLocaleString() : '-'
    }))
    
    pagination.value.total = configs.length
  } catch (error) {
    console.error('加载配置失败:', error)
    message.error('加载配置失败')
    savedConfigs.value = []
  } finally {
    loading.value = false
  }
}

// 删除配置
const deleteConfig = (record) => {
  try {
    const configs = JSON.parse(localStorage.getItem('savedCodeConfigs') || '[]')
    const updatedConfigs = configs.filter(config => config.id !== record.id)
    localStorage.setItem('savedCodeConfigs', JSON.stringify(updatedConfigs))
    message.success('删除成功')
    loadSavedConfigs()
  } catch (error) {
    console.error('删除失败:', error)
    message.error('删除失败')
  }
}

// 跳转到自定义代码生成页面
const goToCustomCodeGeneration = () => {
  router.push('/custom-code-generation')
}

// 编辑配置
const editConfig = (record) => {
  router.push({
    path: '/custom-code-generation',
    query: { 
      id: record.id 
    }
  })
}

// 组件挂载时加载数据
onMounted(() => {
  loadSavedConfigs()
})
onActivated(() => {
  loadSavedConfigs()
})
</script>

<style scoped>
.code-generation-management {
  padding: 20px;
}

.toolbar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}
</style>